package org.rockwalrus.ruly;

import java.text.SimpleDateFormat;

import com.google.wave.api.Annotation;
import com.google.wave.api.Blip;
import com.google.wave.api.Gadget;
import com.google.wave.api.event.DocumentChangedEvent;
import com.google.wave.api.impl.DocumentModifyAction.BundledAnnotation;

public abstract class Handler {
    protected final String keyword;

    protected abstract Gadget createVotingGadget();

    protected final String replacement;
    protected final String kind;
    private final String creationVerb;

    public Handler(String keyword, String replacement, String kind, String creationVerb) {
        this.keyword = keyword;
        this.replacement = replacement;
        this.kind = kind;
        this.creationVerb = creationVerb;

    }

    public String getHelpText() {
        return "Shortcut for creating a " + kind + ": start the blip with \"" + keyword
               + " \")";
    }

    public boolean isTriggered(String text) {
        return text.startsWith("\n" + keyword) && text.length() > keyword.length() + 1;
    }

    public void handleBlip(SimpleDateFormat f, DocumentChangedEvent e, Blip document) {
        replaceTrigger(document);
        addTimestamp(f, e, document);
        
        long deadline = Time.addGameHours(e.getTimestamp(), RulyServlet.VOTING_PERIOD);
        
        addVotingGadget(document, deadline);
        addDeadline(f, document, deadline);
    }

    protected void replaceTrigger(Blip document) {
        document.range(0, keyword.length() + 1)
            .replace(BundledAnnotation.listOf(Annotation.FONT_WEIGHT, "bold"), 
                     "\n" + replacement);
    }

    private void addTimestamp(SimpleDateFormat f, DocumentChangedEvent e, Blip document) {
        String timestamp = f.format(e.getTimestamp());
        document.append("\n\nThis " + kind + ' ' + creationVerb + ' ' + timestamp);
    }

    private void addDeadline(SimpleDateFormat f, Blip document, long deadline) {
        String timestamp = f.format(deadline);
        document.append("\nVoting ends " + timestamp);
    }

    protected void addVotingGadget(Blip document, long deadline) {
        addVotingGadget(document, String.valueOf(deadline));
    }

    protected void addVotingGadget(Blip document, String deadline) {
        Gadget gadget = createVotingGadget();
        
        gadget.setProperty("deadline", deadline);
        document.append(gadget);
    }

}